#pragma once
#include "boost/asio.hpp"
#include <memory>
#include "const.h"
#include "MsgNode.h"
#include <queue>


class CServer;

using boost::asio::ip::tcp;

class CSession:public std::enable_shared_from_this<CSession>
{
public:
    CSession(boost::asio::io_context& ioContext,CServer *server);
    ~CSession();

    tcp::socket& GetSocket();
    
    std::string& GetSessionId();

    // 绑定用户的uid
    void SetUserId(int uid);
    // 获取用户的uid
    int GetUserId();

    void Start();
    void Send(const char* msg,  short max_length, short msgid);
	void Send(std::string msg, short msgid);
    void Close();
	std::shared_ptr<CSession> SharedSelf();
	void AsyncReadBody(int length);
	void AsyncReadHead(int total_len);




//私有方法
private:
    void AsyncReadFull(std::size_t maxLength,std::function<void (const boost::system::error_code& , std::size_t)> handler);
    void AsyncReadLen(std::size_t read_len, std::size_t total_len,
		std::function<void(const boost::system::error_code&, std::size_t)> handler);

    void HandlerWrite(const boost::system::error_code& error, std::shared_ptr<CSession> shared_self);
private:
    boost::asio::ip::tcp::socket _socket;
    std::string _session_id;
    char _data[MAX_LENGTH];
    CServer *_server;

    bool _b_head_parse;
    //接收头部消息的节点
    std::shared_ptr<MsgNode> _recv_head_node;
    //接收消息体的节点
    std::shared_ptr<RecvMsgNode> _recv_msg_node;
    
    bool _b_close;

    //发送消息队列
    std::queue<std::shared_ptr<SendMsgNode>> _send_msg_queue;
    std::mutex _send_lock;
    
    int _user_uid;

};